﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Entity;
using BAL;
using Common;
namespace Web
{
    public partial class GetPayNotify : System.Web.UI.Page
    {
        protected string c_mid;			//商户编号，在申请商户成功后即可获得，可以在申请商户成功的邮件中获取该编号
        protected string c_order;		//商户提供的订单号
        protected string c_orderamount; //商户提供的订单总金额，以元为单位，小数点后保留两位，如：13.05
        protected string c_ymd;			//商户传输过来的订单产生日期，格式为"yyyymmdd"，如20050102
        protected string c_transnum;	//云网支付网关提供的该笔订单的交易流水号，供日后查询、核对使用；
        protected string c_succmark;	//交易成功标志，Y-成功 N-失败
        protected string c_moneytype;	//支付币种，0为人民币
        protected string c_cause;		//如果订单支付失败，则该值代表失败原因
        protected string c_memo1;		//商户提供的需要在支付结果通知中转发的商户参数一
        protected string c_memo2;		//商户提供的需要在支付结果通知中转发的商户参数二
        protected string c_signstr;		//云网支付网关对已上信息进行MD5加密后的字符串
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                c_mid = Request["c_mid"];
                c_order = Request["c_order"];
                c_orderamount = Request["c_orderamount"];
                c_ymd = Request["c_ymd"];
                c_transnum = Request["c_transnum"];
                c_succmark = Request["c_succmark"];
                c_moneytype = Request["c_moneytype"];
                c_cause = Request["c_cause"];
                c_memo1 = Request["c_memo1"];
                c_memo2 = Request["c_memo2"];
                c_signstr = Request["c_signstr"];
                if (c_mid == null || c_order == null || c_orderamount == null || c_ymd == null || c_moneytype == null || c_transnum == null || c_succmark == null || c_signstr == null)
                {
                    lbResult.Text = "支付信息有误 !";
                    Response.End();
                    return;
                }
                //请定义商户号
                string MerchantID;
                MerchantID = System.Configuration.ConfigurationManager.AppSettings["PayId"];

                //请定义支付密钥
                string c_pass;
                c_pass = System.Configuration.ConfigurationManager.AppSettings["PayPass"];

                //校验商户编号
                if (MerchantID != c_mid)
                {
                    lbResult.Text = "提交的商户编号有误 !";
                    Response.End();
                    return;
                }
                //对支付通知信息进行MD5加密
                string srcStr, r_signstr;
                srcStr = c_mid + c_order + c_orderamount + c_ymd + c_transnum + c_succmark + c_moneytype + c_memo1 + c_memo2 + c_pass;
                r_signstr = CNSecurity.EncryptMD5(srcStr);

                //校验商户网站对通知信息的MD5加密的结果和云网支付网关提供的MD5加密结果是否一致
                if (r_signstr != c_signstr)
                {
                    lbResult.Text = "签名验证失败 !";
                    Response.End();
                    return;
                }

                PayLogInfo paylogInfo = PayLog.GetInfoByOrderId(c_order);
                if (paylogInfo == null)
                {
                    lbResult.Text = "订单数据错误 !";
                    Response.End();
                    return;
                }
                if (c_succmark != "Y" && c_succmark != "N")
                {
                    lbResult.Text = "参数提交有误 !";
                    Response.End();
                    return;
                }
                if (c_succmark == "Y")
                {
                    paylogInfo.Status = 1;
                    PayLog.Save(paylogInfo);
                    string code = Utility.GetRandom(100000, 999999).ToString();
                    StudentInfo studentInfo = Student.GetStudentByNumber(paylogInfo.StudentNum);
                    studentInfo.IsPay = 1;
                    studentInfo.VerfiyCode = code;
                    Student.Save(studentInfo);
                    lbResult.Text = "您已成功购买《北京市海淀区义务教育（小学）基础学科 课业诊断报告》，您的查询密码为：" + code + "已发送至邮箱，请您妥善保管，感谢您对孩子的关注和对我们工作的支持！";
                    string emailContent = "您已成功购买《北京市海淀区义务教育（小学）基础学科 课业诊断报告》，您的查询密码为：" + code + "<br/>";
                    emailContent += "请点击<a href='" + System.Configuration.ConfigurationManager.AppSettings["WebUrl"] + "'>查看详情</a>。<br/>";
                    emailContent += "<img scr='" + System.Configuration.ConfigurationManager.AppSettings["WebUrl"] + "/images/content.gif'>";
                    string result = sendMail(paylogInfo.Email, studentInfo.Name, "课业诊断报告购买成功", emailContent);
                }
            }
        }

        private string sendMail(string Recipient, string RecipientName, string Subject, string Body)
        {
            /*
             * *@sohu.com;*@263.net;*@tom.com;*@sina.com;*@126.com;*@21cn.com
             * */
            SmtpMail ESM = new SmtpMail();

            ESM.RecipientName = RecipientName;//设定收件人姓名
            ESM.RecipientMaxNum = 5;


            ESM.AddRecipient(Recipient);//设定收件人地址（必须填写）。
            //ESM.AddRecipient("lion-a@sohu.com","lionsky.net@tom.com");也可以直接传入一个字符串数组，设定一组收件人。


            //System.Configuration.ConfigurationManager.ConnectionStrings[ConnectionStringName].ConnectionString
            String ReplyEMail = System.Configuration.ConfigurationManager.AppSettings["ReplyEMail"];//获取发件人地址
            String ReplyEMailPassword = System.Configuration.ConfigurationManager.AppSettings["ReplyEMailPassword"];//获取发件人邮箱的密码
            String ReplyEMailDomain = System.Configuration.ConfigurationManager.AppSettings["ReplyEMailDomain"];//获取发件人邮箱验证
            ESM.From = ReplyEMail;//设定发件人地址(必须填写)
            ESM.FromName = RecipientName;//设定发件人姓名
            //ESM.AddAttachment("D:\\Project\\ASP.NET\\Exam\\Exam_C\\ReadMe.txt","D:\\Project\\ASP.NET\\Exam\\Exam_C\\新建 文本文档.txt");
            //ESM.ReplyTo=tbReplyTo.Text;//设定回复邮件地址.

            ESM.Priority = "high";//设定优先级，不过我实验着好像没啥用
            ESM.Html = true;//设定正文是否HTML格式。

            ESM.Subject = Subject;//设定邮件主题
            ESM.Body = Body;//设定邮件正文

            ESM.MailDomain = ReplyEMailDomain;//设定SMTP服务器地址
            //也可将将SMTP信息一次设置完成。写成
            //ESM.MailDomain="esmuser:esmpass@smtp.163.com:25";
            ESM.MailServerUserName = ReplyEMail;//设定SMTP验证的用户名
            ESM.MailServerPassWord = ReplyEMailPassword;//设定SMTP验证的密码
            //关于设定SMTP密码：如果在此处不设置的话，也可以在发送时使用在Send()函数的参数中设定。

            //发送Mail，我重载了3次Send函数，可满足不同喜好。
            //1.如果所有的属性都已经设置完毕，可直接使用无参数Send()
            //Send();

            //2.如果尚未设置SMTP服务信息也可使用如下形式设置
            //Send("esmuser:esmpass@smtp.163.com:25")
            //或者省略某些部分Send("esmuser:esmpass@smtp.163.com")或Send("smtp.163.com")

            //3.或者将全部信息都写在Send函数里，不过这样可读性太差了
            //Send(string smtpserver,string from,string fromname,string to,string toname,bool html,string subject,string body)


            //开始发送
            if (ESM.Send())
            {
                return String.Empty;
            }
            else
            {
                return ESM.ErrorMessage;
            }
            //Response.Write(ESM.Logs);

        }
    }
}
